;(function(window, $) {
  'use strict';
  function tagsAd(wrapper, options) {
    var defaults = {
      leadWord: null, //是否包含“全部”分类，该lead分类会始终显示在第一个位置上
      words: null,
      colors: ['#49B4E0', '#FCBDA2', '#EBADBD', '#D5C2AF', '#C0BDE5', '#CBCC7F', '#FFDA7F', '#8dd0c3', '#bbbfc6', '#a4d9ef', '#bbdb98'],
      isFixedWidth: true,
      width: 1000,
      height: 200
    };
    this.options = $.extend(false, defaults, options);
    this.$wrapper = $(wrapper);
    if (!this.$wrapper || this.options.words.length < 1) {
      return false;
    }
    this._create();
    this._bindListener();
    return this;
  };

  tagsAd.prototype = {
    words: [],
    colors: [],
    colorPos: 0,
    _create: function() {
      var opt = this.options,$wrapper = this.$wrapper;
      if (opt.leadWord!==null) {
        if($.isArray(opt.leadWord)){
          this.words = opt.leadWord.concat(this._randArray(opt.words));
        }else{
          this.words = [opt.leadWord].concat(this._randArray(opt.words));
        }
      } else {
        this.words = this._randArray(opt.words);
      }
      //容器宽高初始化
      if (!opt.isFixedWidth) {
        $wrapper.css({width:opt.width,height: opt.height});
      } else {
        // 容器宽高根据父级元素自适应
        var $parent = $wrapper.parent();
        $wrapper.css({width:$parent.width(),height: $parent.height()});
      }
      this._createStyle();
      this.fillRect($wrapper, 0, 0, $wrapper.width(), $wrapper.height(), this.words);
    },

    /*
     * 递归创建box
     */
    fillRect: function(wrapper, left, top, width, height, words) {
      var wordLen = words.length,
        ratio = width / height,
        dot = this._randRange(1, 2, 0.5),
        wordLen1 = Math.round(wordLen * dot[0]),
        wordLen2 = wordLen - wordLen1;

      if (wordLen == 1) {
        this._createBox(wrapper,
          left,
          top,
          width,
          height,
          words[0],
          this._getNextColor());
        return;
      }

      if (wordLen1 == 0) {
        wordLen1 = 1;
        wordLen2--;
      } else if (wordLen2 == 0) {
        wordLen2 = 1;
        wordLen1--;
      }

      if (ratio >= 2.5) {
        // 左右分割
        var leftW = Math.round(width * dot[0]),
          rightW = width - leftW;

        this.fillRect(wrapper,
          left,
          top,
          leftW,
          height,
          words.slice(0, wordLen1));
        this.fillRect(wrapper,
          left + leftW,
          top,
          rightW,
          height,
          words.slice(wordLen1));
      } else {
        // 上下分割
        var topH = Math.round(height * dot[0]),
          bottomH = height - topH;

        this.fillRect(wrapper,
          left,
          top,
          width,
          topH,
          words.slice(0, wordLen1));
        this.fillRect(wrapper,
          left,
          top + topH,
          width,
          height - topH,
          words.slice(wordLen1));
      }
    },
    _createStyle: function(){
      if(!$('#tagsFigureBox').length){
        $('head').append('<style id="tagsAdStyle">.tagsFigureBox{position:relative}.tags-item{position:absolute;text-align:center;word-wrap:break-word;overflow:hidden;border:2px solid #fff}.tags-item a{color:#fff;text-decoration:none;display:block;margin-right:2px;height:100%}</style>');
      }
    },

    /*
     * 创建box
     * @param left、right为box相对于 wrapper 绝对定位的偏移量
     */
    _createBox: function(wrapper, left, top, width, height, word, color) {
      var lineHeight = height,
        paddingTop = 0,
        wordW = this._getWordsWidth(word.title);

      // 如果box中文字的宽度超出box本身的宽度，则需要分多行显示
      if (wordW > width) {
        var line = Math.ceil(wordW / width);
        // 注意设置 line-height 属性和 padding-top 属性
        lineHeight = parseInt(this.$wrapper.css('font-size'));
        lineHeight = lineHeight + lineHeight / 5;
        paddingTop = Math.max(0, (height - line * lineHeight) / 2);
        height -= paddingTop;
      }

      var html = '<span class="tags-item" style="width:' + width + 'px;' +
        'height:' + height + 'px;' +
        'line-height:' + lineHeight + 'px;' +
        'top:' + top + 'px;' +
        'left:' + left + 'px;' +
        'background-color:' + color + ';' +
        (paddingTop ? ('padding-top:' + paddingTop + 'px;') : '') +
        '">' + '<a href="' + word.url + '" >' + word.title + '</a></span>';

      $(wrapper).append(html);
    },

    /* 将base随机分成num份
     * @param base:  被分割的数
     * @param num:   分割的份数     
     * @param round:  base被分割之后两部分的最大差，为了避免每部分太大或太小
     * @param 返回值: 包含num个分界点的数组
     */
    _randRange: function(base, num, round) {
      var center = base / num,
        min = center * (1 - round),
        max = center * (1 + round),
        rand = Math.random() * (max - min) + min;

      if (num == 1) {
        return [base];
      }
      return [rand].concat(this._randRange(base - rand, num - 1, round));
    },


    /*
     * 每次绘制box时获取color列表中下一个颜色值
     */
    _getNextColor: function() {
      var color = this.options.colors[this.colorPos % this.options.colors.length];
      this.colorPos++;
      return color;
    },

    /*
     * 获取指定字体大小的word的宽度，根据该宽度和 box 宽度判断是否分行
     */
    _getWordsWidth: function(word) {
      var tmpObj = $('#tmp_wordW');
      if (tmpObj.size() < 1) {
        $('<span id="tmp_wordW" style="visibility:hidden;font-size:'+this.$wrapper.css('font-size')+'px"></span>').appendTo('body');
      }
      tmpObj.html(word);
      var width = tmpObj.width();
      tmpObj.remove();
      return width;
    },

    /*
     * 随机排列数组元素
     */
    _randArray: function(array) {
      var clone = array.slice(),
        ret = [],
        rand;
      for (var i = 0, len = array.length; i < len; i++) {
        rand = Math.floor(Math.random() * clone.length);
        var tmp = clone[0];
        clone[0] = clone[rand];
        clone[rand] = tmp;
        ret.push(clone[0]);
        clone = clone.slice(1);
      }
      return ret;
    },

    /*
     * 绑定窗口大小改变事件
     */
    _bindListener: function() {
      if (this.options.isFixedWidth) {
        var _this = this,
          timer = null,
          $wrapper = _this.$wrapper;
        $(window).bind('resize', function() {
          if (timer) {
            clearTimeout(window.timer);
            timer = null;
          }
          timer = setTimeout(function() {
            // 响应式 wordbox 根据父级元素宽度和高度的变化来改变自身的宽度和高度，重新绘制
            var $parent = $wrapper.parent();
            if ($wrapper.width() != $parent.width() ||
              $wrapper.height() != $parent.height()) {
              $wrapper.width($parent.width());
              $wrapper.height($parent.height());
              // 清除之前绘制的tagsAd
              $wrapper.empty();
              // 重新绘制tagsAd
              _this.fillRect($wrapper,
                0,
                0,
                $wrapper.width(),
                $wrapper.height(),
                _this.words);
            }
          }, 800);
        });
      }
    }
  };

  window.tagsAd = tagsAd;

  $.fn.tagsAd = function(options) {

    var instance = new tagsAd(this, options);

    if (!instance) {
      console.log("创建失败");
      return null;
    }

    // 返回jquery对象 
    // this指的是应用插件的元素，而不是instance
    return $(this);
  };
})(window, jQuery);

var config = {
  api: 'http://rec.m.sm.cn',
  title: '大白菜',
  query: '大白菜',
  url: 'http://www.kanman.com',
  from: 'wh10275',
  count: 8,
  height: '120px'
}
if(createCORSRequest('get', config.api)){
  $('#tagsWarpBox').show().css({height:config.height,fontSize:'12px',padding:'0 10px 0 6px'});
  $.ajax({
    url: config.api,
    data:{
      app:'related_query',
      type:'json',
      // query: config.query,
      url: config.url,
      // title: config.title,
    count:config.count,
      from: encodeURI(config.from),
      athena_allow_origin:'rec.uc.cn',
      time: Date.now()
    },
    dataType: 'json',
    success: function(res){
      if(res.status===1){
        var colors = ['#49B4E0', '#FCBDA2', '#EBADBD', '#D5C2AF', '#C0BDE5', '#CBCC7F', '#FFDA7F', '#8dd0c3', '#bbbfc6', '#a4d9ef', '#bbdb98'];
        var words = [];
        $.each(res.hits, function(i, v){
          words.push({
            title: v.word,
            url: 'https://so.m.sm.cn/s?q='+v.word+'&from='+config.from
          })
        });
        $('#responsive').tagsAd({
          // leadWord: [{'title': '全部', 'url': ''},{'title': '全部2', 'url': ''}],
          words: words,
          // colors: colors,
          borderWidth: 2,
          isFixedWidth: true,
          width: 800,
          height: 100
        });
      }
    }
  });
}

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // "withCredentials"属性是XMLHTTPRequest2中独有的
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != 'undefined') {
    // 检测是否XDomainRequest可用
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // 看起来CORS根本不被支持
    xhr = null;
  }
  return xhr;
}
